package com.example.manager.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.util.Date;

public class JwtUtils {
    //密钥
    private static final String JWS_SECRET = "SFJOJWIEFJMSDFJISOJFOWOFMWOMEFOWEJFOIWEOFWOEFOWNEOFMON";
    //载荷Key
    private static final String JWS_BODY_KEY = "username";
    //过期时间
    public static long EXPIRATION_TIME = 1000 * 60 * 60 * 24 * 7 ;
    //加密方式
    private static SignatureAlgorithm ALGORITHM = SignatureAlgorithm.HS256;

    /**
     * 生成密钥
     *
     * @return
     */
    private static SecretKey getSecretKey() {
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(JWS_SECRET);
        return new SecretKeySpec(apiKeySecretBytes, ALGORITHM.getJcaName());
    }

    /**
     * 生成token（用户名）
     * @param username
     * @return
     */
    public static String generateToken(String username) {
        //这个时间就是当前时间+30分钟
        Date exprireDate =
                new Date(System.currentTimeMillis() + EXPIRATION_TIME);
        //生成token值
        return Jwts.builder().setHeaderParam("typ", "JWT")
                .claim(JWS_BODY_KEY, username)
                .signWith(ALGORITHM, getSecretKey())
                .setIssuedAt(new Date())
                .expiration(exprireDate).compact();
    }

    /**
     * 根据令牌拿到令牌中的用户名
     * @param token
     * @return
     */
    public static String getUsername(String token) {
        Claims payload = Jwts.parser().verifyWith(getSecretKey()).build().parseSignedClaims(token).getPayload();
        return payload.get(JWS_BODY_KEY).toString();
    }

    /**
     * 判断token是否过期
     *
     * @param token
     * @return
     */
    public static boolean isExpired(String token) {
        try {
            Claims payload = Jwts.parser().verifyWith(getSecretKey()).build().parseSignedClaims(token).getPayload();
            return payload.getExpiration().before(new Date());
        } catch (JwtException e) {
        } catch (IllegalArgumentException e) {
        }
        return true;
    }

    public static void main(String[] args) {
        System.out.println(new BCryptPasswordEncoder().encode("123"));
        String token = generateToken("admin");
        System.out.println(token);
    }
}
